﻿using System;
using System.Threading;
using System.Threading.Tasks;
using MassTransit;
using MassTransitDemo.Shared;

namespace MassTransitDemo.RequestService
{
    class Program
    {
        static async Task Main()
        {
            var busControl = CreateBus();
            var source = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            await busControl.StartAsync();

            try
            {
                while (true)
                {
                    string value = await Task.Run(() =>
                    {
                        Console.WriteLine("Enter message (or quit to exit)");
                        Console.Write("> ");
                        return Console.ReadLine();
                    });

                    if ("quit".Equals(value, StringComparison.OrdinalIgnoreCase))
                        break;

                    var client = CreateRequestClient(busControl);
                    var response = await client.GetResponse<ISimpleResponse>(new SimpleRequest(value));
                    Console.WriteLine("Customer Name: {0}", response.Message.CusomerName);
                }
            }
            finally
            {
                await busControl.StopAsync();
            }
        }

        static IRequestClient<ISimpleRequest> CreateRequestClient(IBusControl busControl)
        {
            var serviceAddress = "rabbitmq://119.3.138.127:5672/masstransitdemo-events-listener";
            var requestClient = busControl.CreateRequestClient<ISimpleRequest>(new Uri(serviceAddress), TimeSpan.FromSeconds(10));
            return requestClient;
        }

        static IBusControl CreateBus()
        {
            var rabbitMQAddress = "119.3.138.127";
            return Bus.Factory.CreateUsingRabbitMq(x => x.Host(rabbitMQAddress, 5672, "masstransitdemo", h =>
            {
                h.Username("masstransitdemo");
                h.Password("masstransitdemo@test");
            }));
        }
    }
}
